const cloud = require('wx-server-sdk')
const dashscope = require('dashscope');

// 初始化云开发，指定环境 ID
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

// 从环境变量中获取 API 密钥
const apiKey = process.env.ALIYUN_QIANFAN_API_KEY;
dashscope.apiKey = apiKey;

exports.main = async (event) => {
    const { userMsg } = event;

    // 记录用户消息
    console.log('Received user message:', userMsg);

    try {
        const response = await dashscope.Generation.call(
            dashscope.Generation.Models.qwenPlus,
            {
                messages: [
                    {
                        role: 'user',
                        content: userMsg
                    }
                ],
                top_p: 0.8,
                temperature: 0.8
            }
        );

        // 记录 API 响应
        console.log('API response:', response);

        if (response.statusCode === 200) {
            return response.output.text;
        } else {
            return { errMsg: `API responded with status ${response.statusCode}: ${response.message}` };
        }
    } catch (error) {
        let errorMessage;
        if (error instanceof dashscope.Error) {
            errorMessage = `Dashscope error: ${error.message}`;
        } else {
            errorMessage = `Unexpected error: ${error.message}`;
        }

        // 记录错误信息
        console.error('Error:', errorMessage);

        return { errMsg: errorMessage };
    }
};